package util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    private static final String LOCK_PREFIX = "lock:";
    private static final long LOCK_EXPIRE_TIME = 10; // 锁的有效时间，单位秒

    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisLock(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     * @param lockKey 锁的key
     * @param requestId 请求的唯一标识（可以是UUID）
     * @return 是否获取锁成功
     */
    public boolean tryLock(String lockKey, String requestId) {
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + lockKey, requestId, LOCK_EXPIRE_TIME, TimeUnit.SECONDS);
        return result != null && result;
    }

        /**
         * 释放锁
         * @param lockKey 锁的key
         * @param requestId 请求的唯一标识（必须是获取锁时使用的同一个）
         * @return 是否释放锁成功
         */
    public boolean releaseLock(String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = stringRedisTemplate.execute(redisScript, Collections.singletonList(LOCK_PREFIX + lockKey), requestId);
        return result != null && result == 1L;
    }

//    @Configuration
//    public static class RedisConfig
//    {
//        @Bean
//        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//            RedisTemplate<String, Object> template = new RedisTemplate<>();
//            template.setConnectionFactory(redisConnectionFactory);
//            template.setKeySerializer(new StringRedisSerializer());
//            template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//            template.setHashKeySerializer(new StringRedisSerializer());
//            template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//            return template;
//        }
//    }
}
